﻿/**
 *  Track Network Map 2.0, NetControl Project 
 *  by Jie Gao, on Dec, 2009.
 * 
 *  Task Manager
 * 
 */

import mx.controls. *;
import mx.events. *;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.core.IUIComponent;
import mx.events.DragEvent;
import mx.managers.DragManager;
import mx.collections. *;
import mx.managers.PopUpManager;
import mx.containers.TitleWindow;
import flash.geom.Point;
import com.esri.ags.Map;
import com.esri.ags.geometry.Extent;
import com.uprr.app.tnm.model.Model;
import com.uprr.app.tnm.events.AppEvent;
import com.uprr.app.tnm.events.EventBus;
 
import com.adobe.serialization.json.JSON

import mx.modules.*; 
import mx.managers.PopUpManager;
import mx.containers.TitleWindow;
import flash.utils.Dictionary;
/**
* bookmark loader
*
* @usage
* @param   event
* @return
*/

public var task:IModuleInfo;
/**
 *  Associtive array to hold all instanciated task objects. clsType is used 
 *  as the key.
 */
private var taskArray:Array = new Array();

/**
 *  task window postion 
 */

private var _x:int=-1;
private var _y:int = -1;


private function init():void {
	// install linstener
	EventBus.addEventListener (AppEvent.TASK_DOUBLECLICK, runTask);
	EventBus.addEventListener (AppEvent.TASK_RELOAD, reloadTasks);
	EventBus.addEventListener (AppEvent.TASK_WINCLOSE, closeWinEventHandler);	
	loadTasks();
}


private function loadTasks():void {
	// disable caching
	var rnd : Number = Math.round(Math.random()*1000);
	var httpRequest:HTTPService =new HTTPService();
		httpRequest.url="GetTasksServlet?x="+rnd;
		
	var parameters:Object=new Object();
	parameters.svcFolder=Model.getInstance ().overlayMapServiceFolder;
	parameters.svcName = Model.getInstance ().overlayMapServiceName;
	
	httpRequest.request=parameters;
	httpRequest.resultFormat="text";
	httpRequest.addEventListener(ResultEvent.RESULT, taskListLoaderResulteHandler);
	httpRequest.addEventListener("fault", serviceFaultHandler);
	httpRequest.send();
}

/**
 * re-load task list once overlay map is changed
 */
private function reloadTasks(event : AppEvent):void {
	Model.getInstance ().taskList.removeAll();
	loadTasks();
}

// Handle WinClose event
public function closeWinEventHandler(event : AppEvent):void {
	var winId:String = event.data as String;
	delete taskArray[winId];
	//taskArray[winId].active = "N";
	//taskArray[winId].taskWin = undefined;
}

/**
 * This method needs to be as public
 * 
 * @param	event
 */
public function runTask(event : AppEvent):void {
	try {
		var item:Object = taskList.selectedItem;
		
		task = ModuleManager.getModule("tasks/" + item.clsType + ".swf");
		task.addEventListener(ModuleEvent.READY, taskReadyEventHandler);
		// where to popup the task win
		//Alert.show("xy:" + event.data.x + "," + event.data.y );
		
		if (event.data.x !=undefined && event.data.y!=undefined) {
				_x = event.data.x;
				_y = event.data.y;
			}	
		
			
		task.load();
		}catch (err : Error) {
			var errorEvent : AppEvent = new AppEvent (AppEvent.APP_ERROR);
			errorEvent.data = "Error when loading tasks: "+err.toString();
			errorEvent.dispatch ();
		}	
	}
	
private function taskReadyEventHandler(e:ModuleEvent):void {
		try {
			
			var item:Object = taskList.selectedItem;
			var taskWin: TaskWindow;
			// if the task has already instatiated
			if (taskArray[item.clsType]==null || taskArray[item.clsType]==undefined){
				taskWin  = TaskWindow (PopUpManager.createPopUp (this, TaskWindow , false));
				taskWin.winId = item.clsType;
				taskWin.mapSvc = item.mapSvc;
				taskWin.title = item.taskName;
				var taskObj:flash.display.DisplayObject = task.factory.create() as flash.display.DisplayObject;
				taskWin.addChild(taskObj);
				taskWin.horizontalScrollPolicy = "off";
				taskArray[item.clsType] = { "taskWin":taskWin, "svc":item.mapSvc, "active":"Y" };
			
				if (_x > 0 && _y > 0) {
					taskWin.x = _x;
					taskWin.y = _y;
				}
				 
			/*
			} 
			else if (taskArray[item.clsType].active == 'N') {
				taskWin = TaskWindow (PopUpManager.createPopUp (this, TaskWindow , false));
				taskArray[item.clsType].active = "Y";
				taskArray[item.clsType].taskWin = taskWin;
				taskWin.addChild(taskArray[item.clsType].taskObj);
				taskArray[item.clsType].taskWin.x = 260;
				taskArray[item.clsType].taskWin.y = 100;
			*/
				
			} else {
							 
				if (_x > 0 && _y > 0) {
					taskArray[item.clsType].taskWin.x= _x;
					taskArray[item.clsType].taskWin.y = _y;
				} else {
					taskArray[item.clsType].taskWin.x = 260;
					taskArray[item.clsType].taskWin.y = 100;
				}
				
			}
			
			// reset the xy 
			_x = -1;
			_y = -1;
			
		} catch (err:Error) {
				var errorEvent : AppEvent = new AppEvent (AppEvent.APP_ERROR);
				errorEvent.data = "Error when creating Task UI: "+err.toString();
				errorEvent.dispatch ();
		}
	}

/**
 * Handel bookmark loading results
 * 
 * @usage   
 * @param   event 
 * @return  
 */

private function taskListLoaderResulteHandler (event : ResultEvent) : void
{
	var rawData : String = String (event.result);
	try 
	{
		var arr : Array = (JSON.decode (rawData) as Array);
		for (var i : int = 0; i < arr.length; i ++)
		{
			Model.getInstance ().taskList.addItem ( 
			{
				clsType : arr [i].clsType, taskName:arr[i].taskName, mapSvc:arr[i].mapSvc
			}
	
			)
		}
	} catch (err : Error)
	{
		var errorEvent : AppEvent = new AppEvent (AppEvent.APP_ERROR);
		errorEvent.data = "Error when loading tasks: "+err.toString();
		errorEvent.dispatch ();
	}
	
}


// when something goes wrong for all HTTP services
private function serviceFaultHandler (event : Event) : void
{
	var errorEvent : AppEvent = new AppEvent (AppEvent.APP_ERROR);
		errorEvent.data = "Error when loading tasks";
		errorEvent.dispatch ();
}

 
// overlay map service click handler
private function taskDoubleClickHandler(event:ListEvent):void {
	var dcEvent : AppEvent = new AppEvent (AppEvent.TASK_DOUBLECLICK);
	dcEvent.data = { "x":260, "y":100 };
	dcEvent.dispatch ();
}

private function taskGridInit(event:FlexEvent):void {
	event.currentTarget.itemRenderer.properties = {doubleClickEnabled:true};
}

